<template>
  <div class="search-results">
    <!-- 结果统计和操作栏 -->
    <div class="results-header">
      <div class="results-info">
        <span class="results-count">
          找到 {{ totalResults }} 个结果
          <span v-if="query" class="search-query">关于 "{{ query }}"</span>
        </span>
        <el-tag v-if="searchType === 'content'" type="info" size="small">
          内容搜索
        </el-tag>
        <el-tag v-else-if="searchType === 'advanced'" type="warning" size="small">
          高级搜索
        </el-tag>
      </div>
      
      <div class="results-actions">
        <el-button-group size="small">
          <el-button @click="selectAll" :disabled="results.length === 0">
            全选
          </el-button>
          <el-button @click="clearSelection" :disabled="selectedItems.length === 0">
            取消选择
          </el-button>
          <el-button 
            type="primary" 
            @click="batchRecover" 
            :disabled="selectedItems.length === 0"
          >
            批量恢复 ({{ selectedItems.length }})
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-state">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-state">
      <el-alert
        :title="error"
        type="error"
        show-icon
        :closable="false"
      />
    </div>

    <!-- 搜索结果列表 -->
    <div v-else-if="results.length > 0" class="results-list">
      <!-- 使用虚拟滚动优化大量结果 -->
      <VirtualScrollList
        v-if="results.length > 50"
        :items="resultsWithId"
        :item-height="120"
        :container-height="600"
        :loading="isLoading"
        :has-more="false"
      >
        <template #default="{ item }">
          <SearchResultItem
            :result="item as any"
            :query="query"
            :is-selected="isSelected(item as any)"
            @toggle-selection="toggleSelection(item as any)"
            @file-select="handleFileSelect(item as any)"
            @recover-file="handleRecoverFile(item as any)"
          />
        </template>
      </VirtualScrollList>
      
      <!-- 常规渲染用于少量结果 -->
      <template v-else>
        <SearchResultItem
          v-for="result in results"
          :key="`${result.versionId}-${result.fileId}`"
          :result="result"
          :query="query"
          :is-selected="isSelected(result)"
          @toggle-selection="toggleSelection(result)"
          @file-select="handleFileSelect(result)"
          @recover-file="handleRecoverFile(result)"
        />
      </template>
    </div>

    <!-- 空结果状态 -->
    <div v-else class="empty-results">
      <el-empty description="没有找到匹配的结果">
        <el-button type="primary" @click="$emit('clear')">
          清空搜索条件
        </el-button>
      </el-empty>
    </div>

    <!-- 分页 -->
    <div v-if="totalResults > pageSize" class="pagination">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[20, 50, 100, 200]"
        :total="totalResults"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
// Icons are imported but not used in template - removing for now
import { ElMessage, ElMessageBox } from 'element-plus'
import VirtualScrollList from './VirtualScrollList.vue'
import SearchResultItem from './SearchResultItem.vue'
import type { SearchResult, ContentSearchResult } from '../types/basic'

interface Props {
  results: (SearchResult | ContentSearchResult)[]
  searchType: 'filename' | 'content' | 'advanced'
  query: string
  totalResults: number
  currentPage: number
  totalPages: number
  pageSize: number
  isLoading: boolean
  error: string | null
}

interface Emits {
  (e: 'pageChange', page: number): void
  (e: 'pageSizeChange', size: number): void
  (e: 'fileSelect', result: SearchResult | ContentSearchResult): void
  (e: 'recoverFile', result: SearchResult | ContentSearchResult): void
  (e: 'batchRecover', results: (SearchResult | ContentSearchResult)[]): void
  (e: 'clear'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const selectedItems = ref<(SearchResult | ContentSearchResult)[]>([])

// 为虚拟滚动添加唯一ID
const resultsWithId = computed(() => {
  return props.results.map((result, index) => ({
    ...result,
    id: `${result.versionId}-${result.fileId}-${index}`
  }))
})

// Removed unused function isContentResult

// 判断项目是否被选中
function isSelected(result: SearchResult | ContentSearchResult): boolean {
  return selectedItems.value.some(item => 
    item.versionId === result.versionId && item.fileId === result.fileId
  )
}

// 切换选择状态
function toggleSelection(result: SearchResult | ContentSearchResult) {
  const index = selectedItems.value.findIndex(item => 
    item.versionId === result.versionId && item.fileId === result.fileId
  )
  
  if (index > -1) {
    selectedItems.value.splice(index, 1)
  } else {
    selectedItems.value.push(result)
  }
}

// 全选
function selectAll() {
  selectedItems.value = [...props.results]
}

// 清空选择
function clearSelection() {
  selectedItems.value = []
}

// 批量恢复
async function batchRecover() {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请先选择要恢复的文件')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要恢复选中的 ${selectedItems.value.length} 个文件吗？`,
      '批量恢复确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    emit('batchRecover', [...selectedItems.value])
    clearSelection()
  } catch {
    // 用户取消
  }
}

// 处理文件选择
function handleFileSelect(result: SearchResult | ContentSearchResult) {
  emit('fileSelect', result)
}

// 处理文件恢复
function handleRecoverFile(result: SearchResult | ContentSearchResult) {
  emit('recoverFile', result)
}

// 处理分页变化
function handleCurrentChange(page: number) {
  emit('pageChange', page)
}

// 处理页面大小变化
function handleSizeChange(size: number) {
  emit('pageSizeChange', size)
}

// Removed unused highlightText function

// Removed unused highlightMatch function



// Removed unused getFileExtension function

// Removed unused formatTimestamp function
</script>

<style scoped>
.search-results {
  width: 100%;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px 16px;
  background-color: var(--el-color-info-light-9);
  border-radius: 8px;
  border: 1px solid var(--el-border-color-light);
}

.results-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.results-count {
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.search-query {
  color: var(--el-color-primary);
  font-weight: normal;
}

.loading-state,
.error-state {
  padding: 20px;
}

.results-list {
  space-y: 12px;
}

.result-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  border: 1px solid var(--el-border-color-light);
  border-radius: 8px;
  background-color: var(--el-bg-color);
  transition: all 0.2s;
  cursor: pointer;
}

.result-item:hover {
  border-color: var(--el-color-primary-light-7);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.result-item.selected {
  border-color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}

.result-checkbox {
  flex-shrink: 0;
  margin-top: 2px;
}

.result-content {
  flex: 1;
  min-width: 0;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  min-width: 0;
}

.file-icon {
  color: var(--el-color-primary);
  flex-shrink: 0;
}

.file-name {
  font-weight: 600;
  color: var(--el-text-color-primary);
  word-break: break-all;
}

.result-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 12px;
  color: var(--el-text-color-regular);
  flex-shrink: 0;
}

.version-id {
  font-family: monospace;
  background-color: var(--el-color-info-light-8);
  padding: 2px 6px;
  border-radius: 4px;
}

.match-score {
  color: var(--el-color-success);
  font-weight: 600;
}

.file-path {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: var(--el-text-color-regular);
  margin-bottom: 8px;
}

.content-matches {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.content-match {
  margin-bottom: 12px;
  padding: 8px;
  background-color: var(--el-color-info-light-9);
  border-radius: 6px;
}

.content-match:last-child {
  margin-bottom: 0;
}

.match-line-number {
  font-size: 12px;
  color: var(--el-color-primary);
  font-weight: 600;
  margin-bottom: 4px;
}

.match-content {
  font-family: monospace;
  font-size: 13px;
  line-height: 1.4;
  margin-bottom: 6px;
}

.match-context {
  margin-top: 6px;
}

.context-line {
  font-family: monospace;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  line-height: 1.3;
  padding-left: 16px;
  border-left: 2px solid var(--el-border-color-lighter);
}

.more-matches {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  font-style: italic;
  text-align: center;
  margin-top: 8px;
}

.result-actions {
  flex-shrink: 0;
}

.empty-results {
  padding: 40px 20px;
  text-align: center;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid var(--el-border-color-lighter);
}

/* 高亮样式 */
:deep(.search-highlight) {
  background-color: var(--el-color-warning-light-8);
  color: var(--el-color-warning-dark-2);
  padding: 1px 2px;
  border-radius: 2px;
  font-weight: 600;
}

:deep(.content-highlight) {
  background-color: var(--el-color-primary-light-8);
  color: var(--el-color-primary-dark-2);
  padding: 1px 2px;
  border-radius: 2px;
  font-weight: 600;
}
</style>